package org.agilelang.generator.javastruts2;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.agilelang.mvc.Generator;
import org.agilelang.mvc.IController;
import org.agilelang.object.Controller;
import org.agilelang.object.Project;
import org.agilelang.object.attributes.View;
import org.agilelang.object.attributes.ViewForm;
import org.agilelang.object.attributes.ViewReport;
import org.agilelang.util.json.JSONException;
import org.agilelang.util.json.JSONObject;

public class GControllerSimple extends Generator implements IController {

    Controller controller;
    String packagefile = "";
    String index = "";
    String struts = "";
    String import_str = "";
    String model_scaffold = "";
    String model_header = "";
    String model_detail = "";

    GControllerSimple(String path_app, Project project, Controller controller) {
        this.path = path_app;
        this.controllers = project.controllers;
        this.appName = project.application.name;
        this.controller = controller;
        this.template2="javastruts2";
    }

    public void process() {
        controller(controller);
    }

    @Override
    public void controller(Controller controller) {

        this.createDirectory(path + File.separator + "web/view/" + controller.name.toLowerCase());
        String views_str = "";
        views_str += view(controller.views, controller.name);
        views_str += viewform(controller.forms, controller.name);
        views_str += viewreport(controller.reports, controller.name);

        String file = readStreamTpl("c_controller.java.tpl");
        file = file.replace("//nameClass//", controller.name);
        file = file.replace("//nameclass//", controller.name.toLowerCase());
        file = file.replace("//views_str//", views_str);
        file = file.replace("//import_str//", import_str);

        createfile("src/java/controller/" + controller.name + "Controller.java", path, file);
    }

    @Override
    public String view(List<View> views, String nameController) {
        String views_str = "";
        int tt = views.size();
        for (int ii = 0; ii < tt; ii++) {
            View view = views.get(ii);
            views_str = views_str
                    + "\tpublic String " + view.name.toLowerCase() + "() {\r\n"
                    + "\t\treturn \"" + view.name.toLowerCase() + "\";\r\n"
                    + "\t}\r\n";
            String file = readStreamTpl("c_view.jsp.tpl");
            file = file.replace("//nameClass_plural//", controller.name);
            file = file.replace("//view//", view.caption);
            createfile(File.separator + "web/view/" + controller.name.toLowerCase() + "/" + view.name.toLowerCase() + ".jsp", path, file);
        }
        return views_str;
    }

    @Override
    public String viewform(List<ViewForm> viewforms, String nameController) {
        String viewforms_str = "";
        String forms_attr_str = "";
        int t = viewforms.size();
        for (int i = 0; i < t; i++) {
            ViewForm view = viewforms.get(i);
            viewforms_str = viewforms_str
                    + "\tpublic String " + view.name.toLowerCase() + "() {\r\n"
                    + "\t\tif (isPost()) {\r\n"
                    + "\t\t}\r\n"
                    + "\t\treturn \"" + view.name.toLowerCase() + "\";\r\n"
                    + "\t}\r\n";
            try {
                JSONObject j = new JSONObject(view.controls);
                Iterator it = j.keys();
                while (it.hasNext()) {
                    String label = (String) it.next();
                    JSONObject d = j.getJSONObject(label);
                    /*forms_attr_str +=
                     TAB + TAB + "<p>\r\n"
                     + TAB + TAB + TAB + "<label for=\"" + label + "\">" + d.get("caption").toString() + " : </label>\r\n"
                     + TAB + TAB + TAB + "<input type=\"text\" name=\"" + label + "\" id=\"" + label + "\" class=\"text ui-widget-content ui-corner-all\"/>\r\n"
                     + TAB + TAB + "</p>\r\n";*/
                    if (d.get("type").toString().equals("text")) {
                        forms_attr_str +=
                                TAB + "<div class=\"control-group\">\r\n"
                                + TAB + TAB + "<label class=\"control-label\" for=\"" + label + "\">" + d.get("caption").toString() + "</label>\r\n"
                                + TAB + TAB + "<div class=\"controls\">\r\n"
                                + TAB + TAB + TAB + "<s:textfield id=\"" + label + "\" name=\"" + label + "\" placeholder=\"" + d.get("caption").toString() + "\"/>\r\n"
                                + TAB + TAB + "</div>\r\n"
                                + TAB + "</div>\r\n";
                    }
                    if (d.get("type").toString().equals("select")) {
                        forms_attr_str +=
                                TAB + "<div class=\"control-group\">\r\n"
                                + TAB + TAB + "<label class=\"control-label\" for=\"" + label + "\">" + d.get("caption").toString() + "</label>\r\n"
                                + TAB + TAB + "<div class=\"controls\">\r\n"
                                + TAB + TAB + TAB + "<s:select id=\"" + label + "\" name=\"" + label + "\" list=\"\"/>\r\n"
                                + TAB + TAB + "</div>\r\n"
                                + TAB + "</div>\r\n";
                    }


                }
            } catch (JSONException ex) {
                Logger.getLogger(GControllerSimple.class.getName()).log(Level.SEVERE, null, ex);
            }

            String file = readStreamTpl("c_view_form.jsp.tpl");
            file = file.replace("//nameClass_plural//", controller.name);
            file = file.replace("//view//", view.caption);
            file = file.replace("//forms_attr_str//", forms_attr_str);

            /*String view_file =
             "<%@taglib uri=\"/struts-tags\" prefix=\"s\"%>\r\n"
             + "<div id=\"contenttab\">\r\n"
             + TAB + "<h2>" + controller.name.toLowerCase() + "  " + view.name.toLowerCase() + "</h2>\r\n"
             + TAB + "<form action=\"\" method=\"post\">\r\n"
             + forms_attr_str
             + TAB + TAB + "<input type=\"submit\" value=\"Submit\" class=\"ui-button ui-widget ui-state-default ui-corner-all\"/>\r\n"
             + TAB + "</form>\r\n"
             + "</div>\r\n";*/

            createfile(File.separator + "web/view/" + controller.name.toLowerCase() + "/" + view.name.toLowerCase() + ".jsp", path, file);
            //createfile("view/" + nameController.toLowerCase() + "/" + view.name + ".html", path, view_file);
        }
        return viewforms_str;
    }

    @Override
    public String viewreport(List<ViewReport> viewreports, String nameController) {

        String views_str = "";
        String getset_str = "";
        int t = viewreports.size();
        for (int i = 0; i < t; i++) {
            ViewReport view = viewreports.get(i);
            if (view.model.equals(this.model_scaffold)) {
                views_str +=
                        "\tpublic String " + view.name.toLowerCase() + "() {\r\n"
                        + "\t\ttotal = " + this.model_scaffold.toLowerCase() + "Dao.count(" + this.model_scaffold.toLowerCase() + ".getName());\r\n"
                        + "\t\t" + this.setPluralize(this.model_scaffold).toLowerCase() + " = " + this.model_scaffold.toLowerCase() + "Dao.query(" + this.model_scaffold.toLowerCase() + ".getName(),page_size, page_number);\r\n"
                        + "\t\treturn \"" + view.name.toLowerCase() + "\";\r\n"
                        + "\t}\r\n";
            } else {
                import_str +=
                        "import model." + view.model + "Model;\n"
                        + "import model.dao." + view.model + "DAO;\n"
                        + "import model.entities." + view.model + ";\n";

                views_str +=
                        "\tpublic String " + view.name.toLowerCase() + "() {\r\n"
                        + "\t\ttotal = " + view.model.toLowerCase() + "Dao.count(" + view.model.toLowerCase() + ".getName());\r\n"
                        + "\t\t" + this.setPluralize(view.model).toLowerCase() + " = " + view.model.toLowerCase() + "Dao.query(" + view.model.toLowerCase() + ".getName(),page_size, page_number);\r\n"
                        + "\t\treturn \"" + view.name.toLowerCase() + "\";\r\n"
                        + "\t}\r\n";
            }

            String textfield_attrs = "", textfield_attrs2 = "";
            String td_attrs = "";
            String th_attrs = "";
            String[] attrs = view.param.split(",");
            int tt = attrs.length;
            for (int j = 0; j < tt; j++) {
                String attr = attrs[j];
                td_attrs += "\t\t\t\t\t\t\t\t<td><s:property value=\"" + attr + "\" /></td> \r\n";
                th_attrs += "<th>" + attr + "</th>";
                textfield_attrs += "\t\t\t<s:textfield id=\"" + attr + "\" label=\"" + attr + "\" name=\"" + attr + "\" onchange = \"document.getElementById('" + attr + "_pdf').value = document.getElementById('" + attr + "').value;\" /> \r\n";
                textfield_attrs2 += "\t<s:hidden id=\"" + attr + "_pdf\" name=\"" + attr + "_pdf\" /> \r\n";

            }
            String file = readStreamTpl("c_report.jsp.tpl");
            file = file.replace("//appname//", this.appName);
            file = file.replace("//nameClass_plural//", this.setPluralize(view.model));
            file = file.replace("//nameclass_plural//", this.setPluralize(view.model).toLowerCase());
            file = file.replace("//td_attrs//", td_attrs);
            file = file.replace("//th_attrs//", th_attrs);
            file = file.replace("//textfield_attrs//", textfield_attrs);
            file = file.replace("//textfield_attrs2//", textfield_attrs2);
            file = file.replace("//link//", view.name);
            file = file.replace("//nameClass_plural//", controller.name);
            file = file.replace("//view//", view.caption);
            createfile(File.separator + "web/view/" + controller.name.toLowerCase() + "/" + view.name.toLowerCase() + ".jsp", path, file);



            String str_forms = "", str_forms2 = "";
            String[] params = view.param.split(",");
            int len = params.length;
            for (int j = 0; j < len; j++) {
                str_forms += "\t\t\t\ttable.addCell(" + view.model.toLowerCase() + ".get" + name(params[j]) + "().toString());\n";
            }
            String str_pdf = "";
            if (view.model.equals(this.model_scaffold)) {
                str_pdf =
                        "\t\t" + this.setPluralize(view.model).toLowerCase() + " = " + view.model.toLowerCase() + "Dao.all();\n";
            } else {
                str_pdf = "\t\t" + this.setPluralize(view.model).toLowerCase() + " = " + view.model.toLowerCase() + "Dao.all();\n";

                getset_str = "\t" + view.model + " " + this.setSingularize(view.model).toLowerCase() + " = new " + view.model + "();\n"
                        + "\tArrayList<" + view.model + "> " + this.setPluralize(view.model).toLowerCase() + " = new ArrayList();\n"
                        + "\t" + view.model + "DAO " + view.model.toLowerCase() + "Dao = new " + view.model + "Model();\n"
                        + "\tpublic " + view.model + " get" + view.model + "() {\n"
                        + "\t\t    return " + this.setSingularize(view.model).toLowerCase() + ";\n"
                        + "\t}\n\n"
                        + "\tpublic void set" + view.model + "(" + view.model + " " + this.setSingularize(view.model).toLowerCase() + ") {\n"
                        + "\t\t    this." + this.setSingularize(view.model).toLowerCase() + " = " + this.setSingularize(view.model).toLowerCase() + ";\n"
                        + "\t}\n\n"
                        + "\tpublic ArrayList<" + view.model + "> get" + this.setPluralize(view.model) + "() {\n"
                        + "\t\t    return " + this.setPluralize(view.model).toLowerCase() + ";\n"
                        + "\t}\n\n"
                        + "\tpublic void set" + this.setPluralize(view.model) + "(ArrayList<" + view.model + "> " + this.setPluralize(view.model).toLowerCase() + ") {\n"
                        + "\t\t   this." + this.setPluralize(view.model).toLowerCase() + " = " + this.setPluralize(view.model).toLowerCase() + ";\n"
                        + "\t}\n\n"
                        + "\tpublic " + view.model + "DAO get" + view.model + "Dao() {\n"
                        + "\t\t    return " + this.setSingularize(view.model).toLowerCase() + "Dao;\n"
                        + "\t}\n\n"
                        + "\tpublic void set" + view.model + "Dao(" + view.model + "DAO " + this.setSingularize(view.model).toLowerCase() + "Dao) {\n"
                        + "\t\t   this." + this.setSingularize(view.model).toLowerCase() + "Dao = " + this.setSingularize(view.model).toLowerCase() + "Dao;\n"
                        + "\t}\n\n";
            }

            views_str +=
                    "\tpublic String " + view.name.toLowerCase() + "PDF() { \n"
                    + str_pdf
                    + "\t\tHttpServletResponse response = ServletActionContext.getResponse();\n"
                    + "\t\tDocument document = new Document();\n"
                    + "\t\tByteArrayOutputStream buffer = new ByteArrayOutputStream();\n"
                    + "\t\ttry {\n"
                    + "\t\t\tPdfWriter.getInstance(document, buffer);\n"
                    + "\t\t\tdocument.open();\n"
                    + "\t\t\tdocument.add(new Paragraph(\"Title\"));\n"
                    + "\t\t\tPdfPTable table = new PdfPTable(" + String.valueOf(len) + ");\n"
                    + "\t\t\tfor (" + view.model + " " + view.model.toLowerCase() + " : " + this.setPluralize(view.model).toLowerCase() + ") {\n"
                    + str_forms
                    + "\t\t\t}\n"
                    + "\t\t\tdocument.add(table);\n"
                    + "\t\t\tdocument.close();\n"
                    + "\t\t} catch (DocumentException e) {\n"
                    + "\t\t\te.printStackTrace();\n"
                    + "\t\t}\n"
                    + "\t\tbyte[] bytes = null;\n"
                    + "\t\tbytes = buffer.toByteArray();\n"
                    + "\t\tresponse.setContentLength(bytes.length);\n"
                    + "\t\tif (bytes != null) {\n"
                    + "\t\t\tinputStream = new ByteArrayInputStream(bytes);\n"
                    + "\t\t}\n"
                    + "\t\treturn \"success\";\n"
                    + "\t}\n"
                    + getset_str;
        }


        return views_str;
    }
}
